<template>
  <Modal :value="modal" @on-ok="submit" @on-visible-change="vchange" :title="modalTitle" width="800">
    <Form :label-width="110" :model="form" ref="form" :rules="rules">
      <Row :gutter="16">
        <Col :md="12">
          <FormItem label="机构" prop="orgId">
            <Select v-model="form.orgId" placeholder="选择机构" @on-change="orgChange" :disabled="modalType !== 1" :transfer="true">
              <OrgTreeOption></OrgTreeOption>
            </Select>
          </FormItem>
        </Col>
        <Col :md="12">
          <FormItem label="事故类型" prop="accidentType">
            <Select v-model="form.accidentType" :disabled="modalType === 0" placeholder="请选择" clearable :transfer="true">
              <Option :value="1" :key="`accidentType-1`">双车剐蹭</Option>
              <Option :value="2" :key="`accidentType-2`">部件失效</Option>
              <Option :value="3" :key="`accidentType-3`">追尾碰撞</Option>
              <Option :value="4" :key="`accidentType-4`">车辆颠覆</Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :md="12">
          <FormItem label="事故编号" prop="accidentNo">
            <Input v-model="form.accidentNo" :disabled="modalType !== 1" :maxlength="20" placeholder="输入事故编号"></Input>
          </FormItem>
        </Col>
        <Col :md="12">
          <FormItem label="事故名称" prop="accidentName">
            <Input v-model="form.accidentName" :disabled="modalType === 0" :maxlength="20" placeholder="输入事故名称"></Input>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :md="12">
          <FormItem label="涉事司机" prop="driverId">
            <Select v-model="form.driverId" :disabled="modalType !== 1" placeholder="请选择司机" :transfer="true">
              <Option v-for="(v,i) in driverList" :key="`accident-driver-${v.id}`" :value="v.id">{{v.name}}</Option>
            </Select>
          </FormItem>
        </Col>
        <Col :md="12">
          <FormItem label="涉事车辆" prop="vehicleId">
            <Select v-model="form.vehicleId" :disabled="modalType !== 1" :multiple="false" placeholder="请选择车辆" :transfer="true">
              <Option v-for="(v,i) in vehicleList" :key="`accident-vehicle-${v.id}`" :value="v.id">{{v.plateNumber}}</Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :md="12">
          <FormItem label="事发时间" prop="incidentTimeStr">
            <DatePicker v-model="form.incidentTimeStr" :readonly="modalType === 0" :disabled="modalType === 0" :options="dateOptions" type="date" :transfer="true" placeholder="请选择事发时间" style="width: 100%"></DatePicker>
          </FormItem>
        </Col>
        <Col :md="12">
          <FormItem label="事发地址" prop="incidentAddress">
            <Input v-model="form.incidentAddress" :disabled="modalType === 0" :maxlength="30" placeholder="输入事发地址"></Input>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :md="12">
          <FormItem label="事发城市" prop="incidentCity">
            <Input v-model="form.incidentCity" :disabled="modalType === 0" :maxlength="20" placeholder="输入事发城市"></Input>
          </FormItem>
        </Col>
        <Col :md="12">
          <FormItem label="事故严重性" prop="accidentLevel">
            <Select v-model="form.accidentLevel" :disabled="modalType === 0" placeholder="请选择" clearable :transfer="true">
              <Option :value="1" :key="`accidentLevel-1`">轻微事故</Option>
              <Option :value="2" :key="`accidentLevel-2`">一般事故</Option>
              <Option :value="3" :key="`accidentLevel-3`">严重事故</Option>
              <Option :value="4" :key="`accidentLevel-4`">特大事故</Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :md="12">
          <FormItem label="损失金额" prop="lossMoney">
            <InputNumber v-model="form.lossMoney" :precision="2" :disabled="modalType === 0" placeholder="输入损失金额" style="width:100%"></InputNumber>
          </FormItem>
        </Col>
        <Col :md="12">
          <FormItem label="处理状态" prop="isProcess">
            <Select v-model="form.isProcess" :disabled="modalType === 0" placeholder="请选择" clearable :transfer="true">
              <Option :value="0" :key="`isProcess-0`">未处理</Option>
              <Option :value="1" :key="`isProcess-1`">已处理</Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :md="24">
          <FormItem label="事件描述" prop="eventDesc">
            <div id="editorContainer" style="width:100%">
            </div>
            <Input type="textarea" v-model="form.eventDesc" style="display:none" />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :md="24">
          <FormItem label="备注" prop="remark">
            <Input v-model="form.remark" type="textarea" :disabled="modalType === 0" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入备注"></Input>
          </FormItem>
        </Col>
      </Row>
    </Form>
    <div slot="footer">
      <Button @click="closeModal">取消</Button>
      <Button type="primary" v-if="modalType" :loading="isSubmiting" @click="submit">保存</Button>
    </div>
  </Modal>
</template>

<script>
  import {mapState,mapActions} from 'vuex'
  import {post}                from '@/util/request'
  import moment                from 'moment'
  import WangEditor from 'wangeditor'
  import config from '@/config'

  export default {
    props:['modal','modalTitle','closeModal','modalType'],
    components:{
      WangEditor
    },
    mounted(){

      let editor = new WangEditor('#editorContainer');
      // editor.customConfig.menus = ['source', '|', 'bold', 'underline', 'italic', 'strikethrough', 'eraser', 'forecolor', 'bgcolor', '|', 'quote', 'fontfamily', 'fontsize', 'head', 'unorderlist', 'orderlist', 'alignleft', 'aligncenter', 'alignright',
      //       '|', 'link', 'unlink', 'table', 'img', 'video', 'insertcode', '|', 'undo', 'redo', 'fullscreen'
      //   ];

      // 显示本地上传
      editor.customConfig.showLinkImg = false;
      editor.customConfig.uploadImgShowBase64 = true;
      editor.customConfig.uploadImgServer = `${config.API_HOST}/common/addPic`;
      // 上传图片配置
      // editor.customConfig.uploadImgUrl = '';
      editor.customConfig.uploadFileName = 'upload';
      // editor.customConfig.uploadImgTimeout = 3000;
      editor.customConfig.uploadImgMaxSize = 4*1024*1024;
      editor.customConfig.onchange = this.editorChange;
      let ths = this;
      editor.customConfig.customAlert = function(info) {
          ths.$Message.error(info);
      }
      editor.customConfig.uploadImgHooks = {
        customInsert: function (insertImg, result, editor) {
            // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
            // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果
            // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
            if(result.success){
              var url = result.data;
              insertImg(url);
            }
        }
      };
      editor.create();
      this.editor = editor;
    },
    data(){
      return {

        editor:null,
        vehicleList:[],
        driverList:[],

        form:{
          id:'',
          orgId:'',
          accidentType:null,
          accidentName:'',
          accidentNo:'',
          driverId:'',
          vehicleId:'',
          incidentTimeStr:'',
          incidentAddress:'',
          incidentCity:'',
          accidentLevel:null,
          lossMoney:null,
          isProcess:null,
          remark:'',
          eventDesc:''
        },
        submitModalForm:{},
        dateOptions:{
          disabledDate(date){
            return date && date.valueOf() > Date.now();
          }
        },
        rules:{
          orgId:{ required: true, message: '机构必填', trigger: 'change' },
          accidentType:{ required: true, type:'number', message: '事故类型必填', trigger: 'change' },
          accidentNo:{ required: true, message: '事故编号必填', trigger: 'change' },
          accidentName:{ required: true, message: '事故名称必填', trigger: 'change' },
          driverId:{ required: true, message: '请先选择机构或选择司机', trigger: 'change' },
          vehicleId:{ required: true, message: '请先选择机构或选择车辆', trigger: 'change' },
          incidentTimeStr:{ required: true, type:'date', message: '事发时间必填', trigger: 'change' },
          incidentAddress:{ required: true, message: '事发地址必填', trigger: 'change' },
          accidentLevel:{ required: true, type:'number', message: '事故严重性必填', trigger: 'change' },
          isProcess:{ required: true, type:'number', message: '处理状态必填', trigger: 'change' },
          eventDesc:{ required: true, message: '事件描述必填', trigger: 'change' },
        }
      }
    },
    computed:{
      ...mapState('accident/accidentList',['viewData','isModalLoading','isSubmiting']),
      ...mapState('base',['userinfo'])
    },
    watch:{
      viewData(v){
        this.form = {...v};
        if(v.incidentTime){
          this.form.incidentTimeStr = moment(v.incidentTime).toDate();
        }
        if(v.lossMoney){
          this.form.lossMoney = (v.lossMoney/100).toFixed(2);
        }
        if(v.eventDesc){
          this.editor.txt.html(v.eventDesc);
          this.editor.$textElem.attr('contenteditable', this.modalType===0?false:true);
        }
      }
    },
    methods:{
      ...mapActions('accident/accidentList',['add','update']),
      vchange(e){
        if(!e){
          this.$refs.form.resetFields();
          this.form = {
            id:'',
            orgId:'',
            accidentType:null,
            accidentName:'',
            accidentNo:'',
            driverId:'',
            vehicleId:'',
            incidentTimeStr:'',
            incidentAddress:'',
            incidentCity:'',
            accidentLevel:null,
            lossMoney:null,
            isProcess:null,
            remark:'',
            eventDesc:''
          };
          this.vehicleList = [];
          this.driverList = [];
          this.editor.txt.html('');
          this.closeModal();
        }
      },
      orgChange(v){
        if(v){
          this.loadVehicles(v);
          this.loadDrivers(v);
        }
      },
      async loadVehicles(orgId){
        let res = await post('/common/findVehicleByOrgId',{'orgIds':orgId});
        this.vehicleList = res.data.data;
      },
      async loadDrivers(orgId){
        let res = await post('/common/findDriverByOrgId',{'orgIds':orgId});
        this.driverList = res.data.data;
      },
      editorChange(html){
        this.form.eventDesc = this.editor.txt.text();
      },
      async submit(){
        let v = await this.$refs.form.validate();
        if(v){
          let res;
          this.submitModalForm = {...this.form};

          this.submitModalForm.plateNumber = this.vehicleList.filter(it=>it.id === this.submitModalForm.vehicleId)[0].plateNumber;
          this.submitModalForm.driverName = this.driverList.filter(it=>it.id === this.submitModalForm.driverId)[0].name;
          this.submitModalForm.incidentTimeStr = moment(this.submitModalForm.incidentTimeStr).format('YYYY-MM-DD');
          this.submitModalForm.lossMoney = this.submitModalForm.lossMoney*100;
          this.submitModalForm.eventDesc = this.editor.txt.html();

          delete this.submitModalForm.insertTime;
          delete this.submitModalForm.updateTime;
          delete this.submitModalForm.incidentTime;

          if(this.modalType === 1)
            res = await this.add(this.submitModalForm);
          else
            res = await this.update(this.submitModalForm);
          if(res.data.success){
            this.closeModal();
            if(this.modalType === 1)
              this.$emit("add");
            else
              this.$emit("edit");
            this.$Message.success('保存成功');
          }else{
            this.$Message.error(res.data.msg);
          }
        }
      }
    }
  }
</script>
